import React, { ReactText, useImperativeHandle, useRef, useState } from 'react';
import { Form, Input, message, Modal } from 'antd';
import { SoundTempInfo } from 'admin/schema/SoundLibrary';
import { createSoundTemp, editSoundTemp, getTTSInfo, getTTSList } from 'admin/servers/servers';
import { clearNull, verifyNull } from 'utils/tools';
import {
  FetchDataParam,
  FetchDataResponse,
  FetchRecordResponse,
  PageSelect,
} from 'components/UILibrary/pageSelect';

type IProps = {
  cRef: any;
};
// 存储回调函数
let ok = () => {};
const SoundTempPop: React.FC<IProps> = ({ cRef }) => {
  const [form] = Form.useForm();
  const ttsSelectRef = useRef<any>();
  const [formData, setFormData] = useState<any>({});
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);
  const open = (obj: SoundTempInfo, cb: any) => {
    setVisible(true);
    ok = cb;
    if (obj.templateId) {
      // 编辑弹窗，需要初始化表单数据，赋值
      setFormData(obj);
      form.setFieldsValue(obj);
      setIsEdit(true);
      // 根据name查找短信模板选项-回显

      setTimeout(() => {
        const { ttsId } = obj;
        if (ttsId) {
          const ttsManufacturerId = ttsId;
          ttsSelectRef.current?.setValue(ttsManufacturerId as number);
        }
      }, 0);
    } else {
      // 新增弹窗，存储versionId或者notifyFlowId
      setFormData(obj);
    }
  };

  useImperativeHandle(cRef, () => ({
    open: (obj: any, cb: any) => open(obj, cb),
  }));
  const handleOK = () => {
    form.validateFields().then(() => {
      console.log('表单验证通过');
      // 表单验证通过
      const val = form.getFieldsValue() as SoundTempInfo;
      // 请求接口
      if (!isEdit) {
        // 创建
        // parseInt
        createSoundTemp(
          clearNull({
            versionId: formData.versionId,
            notifyFlowId: formData.notifyFlowId,
            ...val,
          })
        )
          .then(res => {
            message.success('创建成功');
            // 关闭弹窗
            handleClose();
            // 执行回调刷新
            ok();
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      } else {
        // 修改
        editSoundTemp(formData.templateId, { ...val })
          .then(res => {
            message.success('编辑成功');
            // 关闭弹窗
            handleClose();
            // 执行回调刷新
            ok();
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      }
    });
  };
  const handleClose = () => {
    console.log('点击-关闭');
    // 恢复默认
    setFormData({});
    form.resetFields();
    setVisible(false);
    setIsEdit(false);
  };

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
  };

  /**
   * 查找TTS厂商的dataProvider
   */
  const fetchTTS = (args: FetchDataParam): FetchDataResponse => {
    return new Promise(resolve => {
      getTTSList({
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        ttsManufacturerName: args.keywords,
      })
        .then(res => {
          resolve({
            data: res.data?.map(item => {
              return {
                label: item.ttsManufacturerName,
                value: item.ttsManufacturerId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };
  /**
   * pageSelect setValue时查记录的函数
   */
  const fetchTTSRecord = (ttsManufacturerId: ReactText): FetchRecordResponse => {
    return new Promise(resolve => {
      getTTSInfo(ttsManufacturerId as number).then(res => {
        const item = res.data;
        resolve({
          label: item.ttsManufacturerName,
          value: item.ttsManufacturerId,
          data: item, // 便于onChange判断，有data则回显赋值不用更新数据
        });
      });
    });
  };
  return (
    <Modal
      title={isEdit ? '编辑录音模板' : '添加录音模板'}
      visible={visible}
      onOk={handleOK}
      onCancel={handleClose}
    >
      <Form {...layout} form={form} layout="horizontal">
        <Form.Item
          label="模板名称"
          name="templateName"
          rules={verifyNull('请输入模板名称')}
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
        >
          <Input placeholder="请输入20位内字符" maxLength={20} allowClear />
        </Form.Item>
        <Form.Item noStyle>
          <Form.Item
            label="TTS"
            name="ttsId"
            rules={verifyNull('请选择TTS')}
            extra={<div style={{ color: 'red' }}>话术中的变量将通过TTS播放</div>}
          >
            <PageSelect
              key="ttsSelect"
              ref={ttsSelectRef}
              fetchData={fetchTTS}
              placeholder="请选择TTS"
              fetchRecord={fetchTTSRecord}
              allowClear
            />
          </Form.Item>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default SoundTempPop;
